package com.apise.search;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ResultBuilder {
    public Result build(Document document, String query) {
        String desc = parseDesc(document.getContent(), query);
        return new Result(document.getTitle(), document.getUrl(), desc);
    }

    private String parseDesc(String content, String word) {
        int firstPos = -1;
        content = content.toLowerCase().replaceAll("\\b" + word + "\\b", " " + word + " ");
        firstPos = content.indexOf(" " + word + " ");

        if (firstPos == -1) {
            if (content.length() > 160) {
                return content.substring(0, 160) + "...";
            }

            return content;
        }

        String desc;
        int descFrom = firstPos < 60 ? 0 : firstPos - 60;
        if (descFrom + 160 > content.length()) {
            desc = content.substring(descFrom);
        } else {
            desc = content.substring(descFrom, descFrom + 160) + "...";
        }

        desc = desc.replaceAll("(?i) " + word + " ", "<i>" + word + "</i>");

        return desc;
    }
}
